package com.zeroup.auto;


import static com.zeroup.auto.assists.DouYinBaseStep.packageName;

import android.app.AppOpsManager;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Process;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.StringUtils;
import com.zeroup.auto.app.ZeroneAppliction;
import com.zeroup.auto.assists.DouYinBaseStep;
import com.zeroup.auto.assists.next.LoginVo;
import com.zeroup.auto.bean.User;
import com.zeroup.auto.utils.AjaxResult;
import com.zeroup.auto.utils.AppUtils;
import com.zeroup.auto.utils.ApplicationUtiles;
import com.zeroup.auto.utils.Base64Util;
import com.zeroup.auto.window.FloatService;
import com.zeroup.auto.window.FloatingWindowManager;
import com.ven.assists.Assists;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;

public class MainActivity extends KJActivity {

    FloatingWindowManager floatingWindowManager;

    Boolean isOpen = false;
    Intent mIntent;

    @BindView(id= R.id.login_btn,click = true)
    Button button;

    @BindView(id=R.id.login_username)
    EditText login_username;

    @BindView(id=R.id.login_pwd)
    EditText login_pwd;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏导航栏
        hideNavigationBar();

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Log.i("test","是否白名单"+isIgnoringBatteryOptimizations());
        if(!isIgnoringBatteryOptimizations())
        {
            requestIgnoreBatteryOptimizations();
        }
        floatingWindowManager = new FloatingWindowManager(this);
        Assists.INSTANCE.init(this.getApplication());
        ApplicationUtiles.setActivity(this);
        User dbUser = UserService.findUser(this);
        if(dbUser!=null){
            mIntent = new Intent(MainActivity.this, FloatService.class);
            mIntent.putExtra(FloatService.OPERATION, FloatService.OPERATION_SHOW);
            mIntent.putExtra("uid",dbUser.getUserName());
            mIntent.putExtra("sbh",dbUser.getSbh());
            startService(mIntent);
            finish();
        }
    }

    //查询白名单
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }
    //添加到白名单
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestIgnoreBatteryOptimizations() {
        try {

            Intent intent = new Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:"+getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        // 注册监听器以确保在Activity复位时隐藏导航栏
        getWindow().getDecorView().addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                hideNavigationBar();
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
            }
        });
    }
    private void hideNavigationBar() {
        Window window = this.getWindow();
//这一步最好要做，因为如果这两个flag没有清除的话下面没有生效
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//设置布局能够延伸到状态栏(StatusBar)和导航栏(NavigationBar)里面
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//设置状态栏(StatusBar)颜色透明
        window.setStatusBarColor(Color.TRANSPARENT);
//设置导航栏(NavigationBar)颜色透明
        window.setNavigationBarColor(Color.TRANSPARENT);
    }

    public void btnOpen(View v){
        // 检查是否有悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            // 如果没有权限，则请求权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + this.getPackageName()));
            startActivity(intent);
        }else{
            // 已经获得权限
            AppUtils.isRunKill(this, packageName);
            openFloatWindow();
            this.moveTaskToBack(true);
        }
    }


    private void openFloatWindow(){
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
        } else {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("Loading...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            String user = login_username.getText().toString();
            String shb = login_pwd.getText().toString();
            if(StringUtils.isEmpty(user) || StringUtils.isEmpty(shb)){
                Toast.makeText(MainActivity.this, "请输入账号和设备号~", Toast.LENGTH_SHORT).show();
                return;
            }
            KJHttp kjh = new KJHttp();
            LoginVo vo = new LoginVo();
            vo.setUn(new String(Base64Util.encode(user.getBytes())));
            vo.setSbh(shb);
            vo.setSbCode(DeviceUtils.getUniqueDeviceId());
            HttpParams params = new HttpParams();
            params.putJsonParams(JSON.toJSONString(vo));
            kjh.jsonPost(ZeroneAppliction.apiUrl + "yzyh" ,params, new HttpCallBack() {
                @Override
                public void onLoading(long count, long current) {
                    super.onLoading(count, current);
                }

                @Override
                public void onPreStart() {
                    button.setEnabled(false);
                    dialog.show();
                }

                @Override
                public void onSuccess(String o) {
                    AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                    if(ajaxResult.isSuccess()){
                        User user1 = new User();
                        user1.setSbh(shb);
                        user1.setUserName(ajaxResult.get("id").toString());
                        UserService.saveOrUpdate(MainActivity.this,user1);
                        mIntent = new Intent(MainActivity.this, FloatService.class);
                        mIntent.putExtra(FloatService.OPERATION, FloatService.OPERATION_SHOW);
                        mIntent.putExtra("uid",ajaxResult.get("id").toString());
                        mIntent.putExtra("sbh",shb);
                        startService(mIntent);
                        finish();
                        Toast.makeText(MainActivity.this, "悬浮框已开启~", Toast.LENGTH_SHORT).show();
                        isOpen = true;
                    }else{
                        Toast.makeText(MainActivity.this, ajaxResult.get(AjaxResult.MSG_TAG).toString(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure( int errorNo, String strMsg) {
                    Toast.makeText(MainActivity.this, strMsg, Toast.LENGTH_SHORT).show();

                }
                @Override
                public void onFinish() {
                    button.setEnabled(true);
                    dialog.dismiss();
                }
            });

        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.login);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.login_btn:
                this.btnOpen(v);
                break;
        }
    }
}